﻿using ExcelUnity.Core;
using ExcelUnity.Importer.Results;
using ExcelUnity.Importer.Wrappers;
using System.Collections.Generic;
using System.Linq;

namespace ExcelUnity.Importer
{
    public class CsvErrorStyleGenerator
    {
        private readonly CsvSheet _csvSheet;

        public CsvErrorStyleGenerator(CsvSheet csvSheet)
        {
            _csvSheet = csvSheet;
        }

        public void WriteSheetError(SheetWrapper sheetModel)
        {
            if (sheetModel.HeaderIndex.HasValue)
            {
                _csvSheet.GetRow(sheetModel.HeaderIndex.Value).AppendLastCell("错误信息");
            }

            if (sheetModel.ErrorRows.IsNotNullOrEmpty())
                SetSheetDataErrorStyle(sheetModel.ErrorRows!);

            if (sheetModel.RepeatRowIndexes.IsNotNullOrEmpty())
                SetSheetRowRepeatedErrorStyle(sheetModel.RepeatRowIndexes!, sheetModel.ImportSheet.UniqueValidationPrompt);
        }


        /// <summary>
        /// 错误行样式设置
        /// 设置错误单元格的样式和comment
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="commentDrawing"></param>
        /// <param name="errorRows"></param>
        private void SetSheetDataErrorStyle(IEnumerable<RowWrapper> errorRows)
        {
            foreach (var item in errorRows)
            {
                foreach (var errorCell in item.Cells.Where(x => x.Error.IsNotNullOrWhiteSpace()))
                {
                    _csvSheet.GetRow(item.RowIndex).AppendLastCell(errorCell.Error!);
                }
            }
        }

        /// <summary>
        /// 重复行样式设置
        /// 设置所有重复单元格的样式和重复行第一个重复列的comment
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="commentDrawing"></param>
        /// <param name="rowGroups"></param>
        /// <param name="errorPrompt"></param>
        private void SetSheetRowRepeatedErrorStyle(List<List<RepeatRow>> rowGroups, string errorPrompt)
        {
            foreach (var rowGroup in rowGroups)
            {
                foreach (var repeatRow in rowGroup)
                {
                    var row = _csvSheet.GetRow(repeatRow.RowIndex);
                    var str = $"{errorPrompt}.重复行:{string.Join(",", rowGroup.Where(m => m.RowIndex != repeatRow.RowIndex).Select(m => m.DisplayRowIndex))}";
                    row.AppendLastCell(errorPrompt);
                }
            }
        }
    }
}
